package com.example.myblog.controller.admin;

import com.example.myblog.entity.User;
import com.example.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String loginPage(){
        return "admin/login";
    }

    @PostMapping("/login")
    public ModelAndView login(String userName, String password, HttpSession session){
        ModelAndView mav = new ModelAndView();
        User user = userService.selectByName(userName);
        if (user!=null&&user.getPassword().equals(password)){
            user.setPassword(null);
            session.setAttribute("user",user);
            mav.setViewName("admin/index");
        }else {
            mav.setViewName("redirect:/admin");
            mav.addObject("message","账号或密码有误");
        }
        return mav;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");

        return "redirect:/admin";
    }
}
